package settings

import (
	"fmt"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var Config *AppConfig

type MysqlConfig struct {
	Host string `mapstructure:"host" json:"host"`
	Port int    `mapstructure:"port" json:"port"`

	Username string `mapstructure:"username" json:"username"`
	Password string `mapstructure:"password" json:"password"`
	DBName   string `mapstructure:"db_name" json:"db_name"`
}
type AppConfig struct {
	Port        string      `mapstructure:"port"`
	Mode string `mapstructure:"mode" json:"mode"`
	MysqlConfig MysqlConfig `mapstructure:"mysql" json:"mysql"`
	LogConfig   LogConfig   `mapstructure:"log" json:"log"`
}
type LogConfig struct {
	Level      string `mapstructure:"level" json:"level"`
	Filename   string `mapstructure:"filename" json:"filename"`
	MaxSize    int    `mapstructure:"max_size" json:"max_size"`
	MaxBackups int    `mapstructure:"max_backups" json:"max_backups"`
	MaxAge     int    `mapstructure:"max_age" json:"max_age"`
	LogLevel   string `mapstructure:"log_level" json:"log_level"`
}

func Init() error {
	viper.SetConfigName("config")
	viper.SetConfigType("yaml")
	viper.AddConfigPath(".")
	err := viper.ReadInConfig()
	if err != nil {
		return err
	}
	fmt.Println("配置文件读取成功")
	if err := viper.Unmarshal(&Config); err != nil {
		fmt.Printf("unmarshal conf failed, err:%s \n", err)
	}
	viper.WatchConfig()
	viper.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("配置文件修改了")
		if err := viper.Unmarshal(&Config); err != nil {
			panic(fmt.Errorf("Fatal error config file: %s \n", err))
		}
	})
	return nil
}
